package com.esm.sm800.sm800floating;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.esm.sm800.R;
import com.esm.sm800.activity.ReportbzActivity;
import com.esm.sm800.activity.ReportdzActivity;
import com.esm.sm800.activity.ReporthzActivity;
import com.esm.sm800.activity.ReportjzActivity;
import com.esm.sm800.util.Camera2Manager;
import com.esm.sm800.util.Utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class browserReport extends Activity implements View.OnClickListener {
    private static final int REQUEST_CODE = 1;
    private String usbRootPath = "/mnt/usb_storage/USB_DISK2/udisk0";    // U盘的根目录
    private String usbESMPath = "/mnt/usb_storage/USB_DISK2/udisk0/esm";     // U盘的ESM工作目录

    private TextView button_return;
    private TextView ckbb_bt1_jz;
    private TextView ckbb_bt2_hz;
    private TextView ckbb_bt3_dz;
    private TextView ckbb_bt4_bz;
    private TextView button_setting;

    private static final String ACTION_USB_PERMISSION = "com.sm800.sm800floating.USB_PERMISSION";

    private UsbManager usbManager;
    private UsbDevice mUsbDevice2;
    private PendingIntent permissionIntent;
    private BroadcastReceiver usbReceiver;

    private static final int REQUEST_WRITE_STORAGE = 112;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置Activity为全屏
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_browser_report);

        button_return = (TextView) findViewById(R.id.ckbb_return);
        findViewById(R.id.ckbb_return).setOnClickListener(this);
        ckbb_bt1_jz = (TextView) findViewById(R.id.ckbb_bt1_jz);
        findViewById(R.id.ckbb_bt1_jz).setOnClickListener(this);
        ckbb_bt2_hz = (TextView) findViewById(R.id.ckbb_bt2_hz);
        findViewById(R.id.ckbb_bt2_hz).setOnClickListener(this);
        ckbb_bt3_dz = (TextView) findViewById(R.id.ckbb_bt3_dz);
        findViewById(R.id.ckbb_bt3_dz).setOnClickListener(this);
        ckbb_bt4_bz = (TextView) findViewById(R.id.ckbb_bt4_bz);
        findViewById(R.id.ckbb_bt4_bz).setOnClickListener(this);
        findViewById(R.id.ckbb_clear).setOnClickListener(this);

        // 检测权限
        permissonHandle();
        // 检查U盘是否插入
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        // 检查是否有USB设备连接
        if (usbManager != null) {
            HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
            if (deviceList.size() > 0) {
                // 获取第一个USB设备
                mUsbDevice2 = deviceList.values().iterator().next();
                // 如果存在USB设备，请求权限
                if (mUsbDevice2 != null) {
                    permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
                    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                    registerReceiver(usbReceiver, filter);
                    usbManager.requestPermission(mUsbDevice2, permissionIntent);
                }
            }
        } else {
            Toast.makeText(this, getString(R.string.ckbb_insert_U), Toast.LENGTH_SHORT).show();
        }
        permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_MUTABLE);
        usbReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    createESMDirectory();
                }
            }
        };
        registerReceiver(usbReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));


        // 获取是否数据上传开关
        GlobalUtil.getDatauploadSwitch(this);

        boolean result = createDirectoryIfNotExists(usbESMPath);
        if (result) {
            // 目录存在或创建成功
        } else {
            //Toast.makeText(this, getString(R.string.err_file_createfail), Toast.LENGTH_SHORT).show();
        }

        clearPic();//自动删除三个月前的图片
    }

    public static boolean createDirectoryIfNotExists(String path) {
        File directory = new File(path);
        if (!directory.exists()) {
            return directory.mkdirs();
        }
        return true;
    }

    private void createESMDirectory() {
        File[] storages = this.getExternalFilesDirs(null);
        for (File storage : storages) {
            // 在6.0版本以上，自动创建一个目录，用来作为用户数据存储区域
            // 目录是：/storage/usbhost1-11/Android/data/com.sm800.sm800floating/files/esm
            if (storage.getAbsolutePath().toLowerCase().contains("usb") &&
                    storage.getAbsolutePath().toLowerCase().contains("android")) {
                File uDiskRoot = new File(storage.getAbsolutePath());

                // 外传的U盘工作目录。
                usbESMPath = uDiskRoot.getAbsolutePath() + "/esm";
                // 提取U盘的根目录
                usbRootPath = getUdiskRoot(usbESMPath);

                File newDir = new File(uDiskRoot, "esm");
                if (!newDir.exists()) {
                    newDir.mkdirs();
                }
            }
        }
    }

    // 提取U盘的根目录/storage/usbhost1-20/android/data/com.sm800.sm800floating/files: 取得:/storage/usbhost1-20
    private String getUdiskRoot(String originalString) {
        int startIndex = originalString.indexOf("usb");
        String subString = "";
        if (startIndex != -1) {
            // 找到"usb"后面的第一个斜杠的位置
            int endIndex = originalString.indexOf("/", startIndex + "usb".length());
            if (endIndex != -1) {
                // 截取从字符串开始到"usb"后面的第一个斜杠的子字符串
                subString = originalString.substring(0, endIndex);
                System.out.println(subString);  // 输出：/storage/usbhost1-20
            } else {
                // 如果没有找到斜杠，就截取到字符串末尾
                subString = originalString.substring(0);
                System.out.println(subString);
            }
        } else {
            System.out.println("字符串中不包含'usb'");
        }
        return subString;
    }

    // Manifest.permission.ACCESS_COARSE_LOCATION
    private void permissonHandle() {
        //安卓6.0权限请求
        // 检查是否已经拥有所需的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE);
        } else {
            // 已拥有所需权限，可以执行文件操作
            createESMDirectory();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (requestCode == REQUEST_WRITE_STORAGE) {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 用户授权了权限，可以执行文件操作copyFile
                        createESMDirectory();
                    } else {
                        Toast.makeText(this, getString(R.string.ckbb_write_external_permission), Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                // 用户拒绝了权限请求
                Log.e("UsbCheckReceiver", "Permission denied.");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbReceiver);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ckbb_return:
//                startService(new Intent(browserReport.this, BackService.class));
//                moveTaskToBack(true);
                finish();
                break;
            case R.id.ckbb_bt1_jz:
                Intent intent1 = new Intent(browserReport.this, ReportjzActivity.class);
                intent1.putExtra("usbRootPath", usbRootPath); // 添加参数
                intent1.putExtra("usbESMPath", usbESMPath);   //添加参数
                intent1.putExtra("reportType", 1);      //添加参数
                startActivity(intent1);
                break;
            case R.id.ckbb_bt2_hz:
                Intent intent2 = new Intent(browserReport.this, ReporthzActivity.class);
                intent2.putExtra("usbRootPath", usbRootPath); // 添加参数
                intent2.putExtra("usbESMPath", usbESMPath);   //添加参数
                intent2.putExtra("reportType", 2);      //添加参数
                startActivity(intent2);
                break;
            case R.id.ckbb_bt3_dz:
                Intent intent3 = new Intent(browserReport.this, ReportdzActivity.class);
                intent3.putExtra("usbRootPath", usbRootPath); // 添加参数
                intent3.putExtra("usbESMPath", usbESMPath);   //添加参数
                startActivity(intent3);
                break;
            case R.id.ckbb_bt4_bz:
                //ReportbzActivity
                Intent intent4 = new Intent(browserReport.this, ReportbzActivity.class);
                intent4.putExtra("usbRootPath", usbRootPath); // 添加参数
                intent4.putExtra("usbESMPath", usbESMPath);   //添加参数
//                Intent intent4 = new Intent(browserReport.this, browser_bz_report.class);
//                intent4.putExtra("usbRootPath", usbRootPath); // 添加参数
//                intent4.putExtra("usbESMPath", usbESMPath);   //添加参数
                startActivity(intent4);
                break;
            case R.id.ckbb_clear:
                clearPic();
                break;
        }
    }

    //自动删除三个月前的图片
    private void clearPic() {
        String path = Camera2Manager.get().getFilesPath(getBaseContext()) + "/ESMJPG/";
        String mmdir = getmmdir();
        path = path + mmdir + "/";
        File dir1 = new File(path);
        if (dir1.exists()) {
            Utils.deleteDir(path);
        }
    }

    String getmmdir() {
        Date currentDate = new Date();
        // 创建一个Calendar对象，并设置其时间为当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        // 减去3个月
        calendar.add(Calendar.MONTH, -3);
        // 获取3个月前的日期
        Date threeMonthsAgo = calendar.getTime();
        // 格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        String formattedDate = dateFormat.format(threeMonthsAgo);

        return formattedDate;
    }

}